#include "stdafx.h"
#include "ui_multi_timer.h"

_SSL_BEGIN
_SSUIL_BEGIN

typedef struct find_timer_by_id
{
	find_timer_by_id(unsigned int id)
		: timer_id(id)
	{

	}

	bool operator()(const UITimerInfo &info)
	{
		return timer_id == info.id;
	}

	unsigned int timer_id;
} find_timer_by_id;

UIMultiTimer::UIMultiTimer()
{
	auto_timer_id_index_ = kMaxSysTimerID;
}

UIMultiTimer::~UIMultiTimer()
{
	KillIDTimer();
}

void UIMultiTimer::OnTimer(unsigned int interval)
{
	UITimerInfos timer_infos;
	timer_infos_lock_.enter();
	timer_infos = timer_infos_;
	timer_infos_lock_.leave();

	for(UITimerInfos::iterator iter=timer_infos.begin(); iter!=timer_infos.end(); iter++)
	{
		iter->elpase += interval;
		if(iter->elpase >= iter->interval)
		{
			iter->elpase = 0;
			OnTimerCB(iter->id);
		}

		UITimerInfos::iterator iter2 = std::find_if(timer_infos_.begin(), timer_infos_.end(), find_timer_by_id(iter->id));
		if(iter2 != timer_infos_.end())
		{
			iter2->elpase = iter->elpase;
		}
	}
}

int UIMultiTimer::SetIDTimer(unsigned int timer_id, unsigned int elapse)
{
	unsigned int id = timer_id;
	if(id == 0)
		id = auto_timer_id_index_++;
	CsLockGuard(timer_infos_lock_);
	UITimerInfos::iterator iter = std::find_if(timer_infos_.begin(), timer_infos_.end(), find_timer_by_id(id));
	if(iter == timer_infos_.end())
	{
		UITimerInfo tinfo;
		tinfo.id = id;
		tinfo.interval = elapse;
		tinfo.elpase = 0;
		timer_infos_.push_back(tinfo);
		iter = std::find_if(timer_infos_.begin(), timer_infos_.end(), find_timer_by_id(id));
		SS_ASSERT(iter != timer_infos_.end());
		TrySetTimerOnWindowManager();
	}
	return id;
}

bool UIMultiTimer::KillIDTimer(unsigned int timer_id /* = 0 */)
{
	CsLockGuard(timer_infos_lock_);
	UITimerInfos::iterator iter = std::find_if(timer_infos_.begin(), timer_infos_.end(), find_timer_by_id(timer_id));
	if(iter == timer_infos_.end())
		return false;
	timer_infos_.erase(iter);
	if(timer_infos_.size() == 0)
	{
		KillTimerOnWindowManager();
	}
	return true;
}


_SSUIL_END
_SSL_END
